<script setup lang="ts">
defineOptions({
  name: "GAS_OPERATION_DETECTORMANAGE_LEDGERMANAGE"
});

import { ref, onMounted, onUnmounted, markRaw, getCurrentInstance } from "vue";
import { queryDetectorLedgerList } from "@/api/modules/operation";
import commonSearch from "@/views/common/components/commonSearch/index.vue";
import commonTable from "@/views/common/components/commonTable/index.vue";
import { Edit } from "@px-ui/icons-vue";
import { PxMessage, PxMessageBox } from "px-ui";
import { useTableCloumns, useSearchOption } from "./hooks";
import { useUpdateDomHeight, useCancelUpdateDomHeight } from "@/hooks/useCommon";
import { useThrottleFn } from "@vueuse/core";
import { throttleDelay as delay } from "@/utils/constant";
import curve from "./components/curve.vue";
import edit from "./components/edit.vue";
import checkFiles from "./components/checkFiles.vue";
import checkLogs from "@/views/gas/components/checkLogs.vue";

const showAllFiles = (data: any) => {
  checkFilesIds.value = data.map(item => item.id);
  checkFilesDialogVisible.value = true;
};

const searchLoading = ref<boolean>(false);
const gap = 88;
const defaultHeight = 606;
const tableContentRef = ref<HTMLElement | null>(null);
const commonTableRef = ref<CommonTable.TableRefType>(null);
const commonSearchRef = ref<CommonSearch.SearchFormRefType>(null);
const scrollbarHeight = ref<number>(defaultHeight);
const searchOption = ref<Array<CommonSearch.SearchOption>>(useSearchOption());
const tableCloumns = ref<Array<CommonTable.TableCloumnsType>>(useTableCloumns(false, showAllFiles));
const params = ref<any>({});
const detectorCode = ref<string>("");
const ids = ref<Array<any>>([]);
const checkFilesIds = ref<Array<any>>([]);
const gasName = ref<string>("");
const detectorCodeList = ref<Array<any>>([]);
const list = ref<Array<any>>([]);
const calibrationDate = ref<string>("");
const calibrationDateHistory = ref<string>("");

const signCycle = ref<number>(0);
const timeLimit = ref<number>(0);
const curveDialogVisible = ref<boolean>(false);
const editDialogVisible = ref<boolean>(false);
const batchEdit = ref<boolean>(false);
const checkFilesDialogVisible = ref<boolean>(false);
const checkLogsDialogVisible = ref<boolean>(false);

const operationOptions: Array<CommonTable.operationOptionItemType> = [
  {
    content: "编辑",
    auth: "GAS_OPERATION_DETECTORMANAGE_LEDGERMANAGE_EDIT_BTN",
    icon: markRaw(Edit),
    click: (scope: any) => editFn(scope)
  }
];

let defaultParams: any = {};
let currentParams: any = {};

const getRowKey = row => {
  return row.detectorCode;
};

const headerCellStyleFn = ({ row, column, rowIndex, columnIndex }: CommonTable.CellType): Record<string, string> => {
  const style: any = {};
  if (columnIndex === 6) {
    style["text-align"] = "center";
  }
  return style;
};

const cellStyleFn = ({ row, column, rowIndex, columnIndex }: CommonTable.CellType): Record<string, string> => {
  const style: any = {};
  if (columnIndex === 6) {
    const { replaceReminder = false } = row;
    if (replaceReminder) {
      style["background-color"] = "#FEECEC";
      style["color"] = "#EF4444";
    }
  } else if (columnIndex === 11) {
    const { calibrationReminder = false } = row;
    if (calibrationReminder) {
      style["background-color"] = "#FEECEC";
      style["color"] = "#EF4444";
    }
  }
  return style;
};

const updateParams = () => {
  params.value = { ...defaultParams, ...currentParams };
};

const submitSearchFormHandler = (form: any) => {
  currentParams = { ...currentParams, ...form };
  updateParams();
};

const resetSearchFormHandler = () => {
  currentParams = {};
  updateParams();
};

const { proxy }: any = getCurrentInstance();

const batchExportFn = useThrottleFn(async () => {
  if (detectorCodeList.value?.length) {
    const url = "/operation/api/v1/gas/detector/exportData";
    const detectorCodes = detectorCodeList.value;
    const params = { detectorCodes };
    proxy.download("post", url, params);
    PxMessageBox.alert("正在导出您筛选的数据，数据处理可能需要一定时间，请耐心等待，数据准备完毕将直接下载。", "批量导出", {
      confirmButtonText: "我知道了"
    });
  } else {
    PxMessage.error("请选择侦测器！！");
  }
}, delay);

const batchEditFn = () => {
  if (detectorCodeList.value?.length) {
    batchEdit.value = true;
    list.value = [...detectorCodeList.value];
    editDialogVisible.value = true;
  } else {
    PxMessage.warning("请选择侦测器！");
  }
};

const checkLogsFn = () => {
  checkLogsDialogVisible.value = true;
};

const generateCurveFn = useThrottleFn(async () => {
  if (detectorCodeList.value?.length) {
    curveDialogVisible.value = true;
  } else {
    PxMessage.warning("请选择侦测器！");
  }
}, delay);

const editSubmitHandler = () => {
  commonTableRef.value.clearSelection();
  commonTableRef.value.queryTableData(null, true);
};

const selectionChangeHandler = (val: Array<any>) => {
  detectorCodeList.value = [];
  if (val?.length) {
    detectorCodeList.value = val.map(item => item.detectorCode);
  }
};

const editFn = scope => {
  const {
    row: {
      detectorCode: detectorCode_ = "",
      fileDTOList = [],
      gasName: gasName_ = "",
      strCalibrationDate = "",
      calibrationDateHistory: calibrationDateHistory_ = "",
      signCycle: signCycle_ = 0,
      timeLimit: timeLimit_ = 0
    }
  } = scope;
  batchEdit.value = false;
  detectorCode.value = detectorCode_;
  ids.value = fileDTOList?.map(item => item.id);
  gasName.value = gasName_;
  calibrationDate.value = strCalibrationDate;
  calibrationDateHistory.value = calibrationDateHistory_;
  signCycle.value = signCycle_;
  timeLimit.value = timeLimit_;
  editDialogVisible.value = true;
};

onMounted(async () => {
  await useUpdateDomHeight(scrollbarHeight, tableContentRef, gap, defaultHeight);
});

onUnmounted(() => useCancelUpdateDomHeight());
</script>

<template>
  <div v-loading="searchLoading" class="ledger-manage">
    <div class="ledger-manage-search">
      <commonSearch
        v-if="searchOption?.length"
        ref="commonSearchRef"
        v-model:loading="searchLoading"
        :row-num="4"
        :operation-span="3"
        :option="searchOption"
        @submit="submitSearchFormHandler"
        @reset="resetSearchFormHandler"
      />
    </div>
    <div class="ledger-manage-btns">
      <px-button v-has="'GAS_OPERATION_DETECTORMANAGE_LEDGERMANAGE_EXPORT_BTN'" type="primary" plain @click="batchExportFn">批量导出</px-button>
      <px-button v-has="'GAS_OPERATION_DETECTORMANAGE_LEDGERMANAGE_BATCH_EDIT_BTN'" type="primary" plain @click="batchEditFn">批量编辑</px-button>
      <px-button v-has="'GAS_OPERATION_DETECTORMANAGE_LEDGERMANAGE_CURVE_BTN'" type="primary" plain @click="generateCurveFn">生成曲线</px-button>
      <px-button v-has="'GAS_OPERATION_DETECTORMANAGE_LEDGERMANAGE_CHECKLOGS_BTN'" type="primary" plain @click="checkLogsFn">查看日志</px-button>
    </div>
    <div ref="tableContentRef" class="ledger-manage-table">
      <commonTable
        ref="commonTableRef"
        indexNeed
        selection
        :operationOptions="operationOptions"
        :tableCloumns="tableCloumns"
        :height="scrollbarHeight"
        :header-cell-style="headerCellStyleFn"
        :cell-style="cellStyleFn"
        :row-key="getRowKey"
        :axiosApi="queryDetectorLedgerList"
        :params="params"
        @selection-change="selectionChangeHandler"
      />
    </div>
    <curve v-if="curveDialogVisible" v-model="curveDialogVisible" :detectorCodeList="detectorCodeList" />
    <edit
      v-if="editDialogVisible"
      v-model="editDialogVisible"
      :batch="batchEdit"
      :detectorCode="detectorCode"
      :gasName="gasName"
      :ids="ids"
      :calibrationDate="calibrationDate"
      :calibrationDateHistory="calibrationDateHistory"
      :signCycle="signCycle"
      :timeLimit="timeLimit"
      :detectorCodeList="list"
      @submit="editSubmitHandler"
    />
    <checkFiles v-if="checkFilesDialogVisible" v-model="checkFilesDialogVisible" :ids="checkFilesIds" />
    <checkLogs v-if="checkLogsDialogVisible" v-model="checkLogsDialogVisible" type="侦测器台账" />
  </div>
</template>

<style lang="scss" scoped>
.ledger-manage {
  box-sizing: border-box;
  width: 100%;
  padding: 16px;
  background-color: #fff;

  .ledger-manage-search {
    width: 100%;
  }

  .ledger-manage-btns {
    display: flex;
    align-items: center;
    margin-top: 16px;
  }

  .ledger-manage-table {
    margin-top: 16px;
  }
}
</style>
